/*
 * Copyright 2009 Jesse McLaughlin (nzjess@gmail.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.travelfusion.xmlclient.ri.handler.plane;

import java.util.ArrayList;

import org.travelfusion.xmlclient.handler.HandlesRequestsFor;
import org.travelfusion.xmlclient.impl.handler.AbstractXmlToolRequestXmlToolResponseHandler;
import org.travelfusion.xmlclient.ri.xobject.plane.XDropInParam;
import org.travelfusion.xmlclient.ri.xobject.plane.XProcessDetailsRequest;
import org.travelfusion.xmlclient.ri.xobject.plane.XProcessDetailsResponse;

import com.mycila.xmltool.CallBack;
import com.mycila.xmltool.XMLTag;

/**
 * @author Jesse McLaughlin (nzjess@gmail.com)
 */
@HandlesRequestsFor(XProcessDetailsRequest.class)
public class ProcessDetailsHandler extends AbstractXmlToolRequestXmlToolResponseHandler<XProcessDetailsRequest, XProcessDetailsResponse> {

  public ProcessDetailsHandler() {}

  @Override
  protected void fillTemplate() throws Exception {
    template.gotoChild();
    template.gotoChild("RoutingId").addText(request.getRoutingId());
    template.gotoChild("OutwardId").addText(request.getOutwardId());
    if (request.getReturnId() != null) {
      template.gotoChild("ReturnId").addText(request.getReturnId());
    }
    else {
      template.gotoChild("ReturnId").delete();
    }
  }

  public XProcessDetailsResponse handleResponse() throws Exception {
    final XProcessDetailsResponse response = new XProcessDetailsResponse();

    responseTag.gotoChild("ProcessDetails").gotoChild("SupplierHandoffData");

    response.setHttpMethod(responseTag.getText("Method"));
    response.setUrl(responseTag.getText("Url"));

    response.setParams(new ArrayList<XDropInParam>());
    responseTag.gotoChild("ParameterList").forEachChild(new CallBack() {
      public void execute(XMLTag childTag) {
        XDropInParam xDropInParam = new XDropInParam();
        xDropInParam.setName(childTag.getText("Name"));
        xDropInParam.setValue(childTag.getText("Value"));
        response.getParams().add(xDropInParam);
      }
    });

    return response;
  }
}
